<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：{{ total }}条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button
                type="warning"
                size="small"
                @click="$router.push('/import')"
              >
                导入excel
              </el-button>
              <el-button
                ::loading="downloadLoading"
                type="danger"
                size="small"
                @click="exportDate"
              >
                导出excel
              </el-button>
              <el-button type="primary" size="small" @click="addEmp">
                新增员工
              </el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table
            border
            :default-sort="{ prop: 'workNumber', order: 'descending' }"
            :data="list"
          >
            <el-table-column type="index" label="序号" />
            <el-table-column prop="username" label="姓名" />
            <el-table-column prop="workNumber" label="工号" />
            <el-table-column label="聘用形式">
              <template #default="{ row }">
                {{ typeForm(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column sortable prop="correctionTime" label="入职时间" />
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button
                  type="text"
                  size="small"
                  @click="$router.push(`employees/detail/${row.id}`)"
                >
                  查看
                </el-button>
                <el-button type="text" size="small">分配角色</el-button>
                <el-button type="text" size="small" @click="delEmp(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              background
              :total="total"
              :current-page="query.page"
              :page-size="query.size"
              :page-sizes="[10, 5, 2]"
              layout="prev, pager, next, sizes"
              @current-change="changePage"
              @size-change="changeSize"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <AddEmp :show-dialog="showDialog" @close-dialog="showDialog = $event" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
// 导入枚举
import EnubTypes from '@/api/constant/employees'
// 导入新增弹层组件
import AddEmp from './components/add-employee.vue'
console.log('枚举: ', EnubTypes.hireType)
export default {
  components: {
    AddEmp
  },
  data () {
    return {
      // 导出状态
      downloadLoading: false,
      // 新增弹层显示隐藏
      showDialog: false,
      // 账户状态
      qy: true,
      // 员工列表
      list: [],
      // 总记录数
      total: 0,
      // 分页
      query: {
        page: 1, // 当前页
        size: 10 // 每页条数
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 导出员工
    async exportDate () {
      // 开始导出
      this.downloadLoading = true
      const userMap = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(userMap)
      const enHeader = Object.values(userMap)
      console.log(header, enHeader)
      const data = this.transFormArray(this.list, enHeader)
      console.log('二维数组: ', data)
      const excel = await import('@/utils/Export2Excel')
      console.log('excel导出方法: ', excel)
      excel.export_json_to_excel({
        // 表头 必填
        // header: ['姓名', '工资'],
        header,
        // 表头对应的具体数据 必填
        // data: [
        //   ['刘备', 100],
        //   ['关羽', 500]
        // ],
        data,
        filename: 'excel-list', // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx' // 导出生成的文件类型
      })

      // 导出完成
      this.downloadLoading = false
    },
    // 处理导出的数据list(转换成二维数组)
    transFormArray (list, enHeader) {
      // 定义一个二维数组
      const secondArray = []
      list.forEach(user => {
        const userArray = []
        for (const key in user) {
          if (enHeader.includes(key)) {
            // 处理聘用关系=>转换数字
            if (key === 'formOfEmployment') {
              userArray.push(this.typeForm(user[key]))
            } else {
              userArray.push(user[key])
            }
          }
        }
        secondArray.push(userArray)
      })
      return secondArray
    },
    // 新增员工
    addEmp () {
      this.showDialog = true
    },
    // 删除员工
    async delEmp (row) {
      console.log('要删除的员工: ', row)
      try {
        await this.$confirm(`确定要删除${row.username}吗?`)
        // 确认走到这
        await delEmployee(row.id)
        const newPage = Math.ceil((this.total - 1) / this.query.size)
        if (this.query.page > newPage) {
          this.query.page = newPage
        }
        this.getList()
        this.$message.success('删除成功')
        // this.query.page = 1
      } catch (error) {
        console.log(error)
      }
    },
    // 转换聘用形式
    typeForm (type) {
      // 通过map映射得到想要的数据类型
      const map = {}
      EnubTypes.hireType.forEach((item) => {
        map[item.id] = item.value
      })
      console.log(map)
      return map[type]
    },
    // 当前页码
    changePage (currPage) {
      console.log(currPage)
      this.query.page = currPage
      this.getList()
    },
    // 每页条数
    changeSize (currSize) {
      console.log(currSize)
      this.query.size = currSize
      this.getList()
    },
    // 获取员工列表
    async getList () {
      const { total, rows } = await getEmployeeList(this.query)
      // console.log('员工列表: ', rows)
      this.total = total
      this.list = rows
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
